//
//  RecFoundViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/23.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "RecFoundViewController.h"
#import "PKImagePickerViewController.h"
#import "LocationManagement.h"
#import "CommonService.h"
#import "LPUtils.h"
#import "SCNavigationController.h"
#import "PostViewController.h"
#import "LoginViewController.h"
#import "UserEntity.h"
#import "LoginViewController.h"
#import "ZYQAssetPickerController.h"
#import "SelectParkViewController.h"
#import <AVFoundation/AVFoundation.h>
#define MAXIMAGENUM 6
@interface RecFoundViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate, SCNavigationControllerDelegate, UITextFieldDelegate,UINavigationControllerDelegate,UINavigationBarDelegate,ZYQAssetPickerControllerDelegate>

@property (nonatomic, strong) IBOutlet UITextView *textViewTitle;
@property (nonatomic, strong) PKImagePickerViewController *imagePicker;
@property (nonatomic, strong) IBOutlet UIButton *btnSelectImage;
@property (nonatomic, strong) IBOutlet UITextField *textFieldSite;
@property (nonatomic, strong) IBOutlet UITextField *textFieldPark;
@property (nonatomic, strong) IBOutlet UIImage *imageYJ;
@property (nonatomic, strong) ZYQAssetPickerController *picker;
//@property (nonatomic, strong) NSMutableArray *assertarr;
@property (nonatomic, strong) NSMutableArray *imageArray_selected;

@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation RecFoundViewController
@synthesize textViewTitle, imagePicker, btnSelectImage;
@synthesize textFieldSite, textFieldPark, imageYJ;
@synthesize parkSelect;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"发布";
    //self.textViewTitle.placeholder = @"Type some text";
    //[self.textViewTitle becomeFirstResponder];
    self.imageArray_selected = [[NSMutableArray alloc]init];
    [self.textViewTitle.layer setMasksToBounds:YES];
    [self.textViewTitle.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [self.textViewTitle.layer setBorderWidth:0.5]; //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.77, 0.77, 0.77, 1 });
    [self.textViewTitle.layer setBorderColor:colorref];//边框颜色
    
    UIButton *btnSave =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    [btnSave setTitle:@"发表" forState:UIControlStateNormal];
    //定义按钮标题字体格式
    [btnSave.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
    [btnSave setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnSave addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *nextButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnSave];
    self.navigationItem.rightBarButtonItem = nextButtonItem;
    
    textFieldSite.delegate = self;
    
    //选择公园边框
    parkSelect.layer.cornerRadius = 5.0f; //圆角半径
    parkSelect.layer.masksToBounds = YES; //圆角
    parkSelect.layer.borderWidth = 0.5f; //边框宽度
    parkSelect.layer.borderColor = [[UIColor grayColor]CGColor]; //边框颜色
    if (self.parkEntity.title.length > 0) {
        [self.parkSelect setTitle:self.parkEntity.title forState:UIControlStateNormal];
    }
    self.selectIndex = -1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)doSelectPhoto:(UIButton*)sender
{
    [self.view endEditing:YES];
    UIActionSheet *actSheet = nil;
    if (sender.tag < [self.imageArray_selected count])
    {
        actSheet = [[UIActionSheet alloc]initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从本地相册选取",@"删除", nil];
    }
    else
    {
        actSheet = [[UIActionSheet alloc]initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从本地相册选取", nil];
    }
    [actSheet showInView:self.view];
    actSheet.delegate = self;
    actSheet.tag = sender.tag;
}

#pragma actionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    self.selectIndex = actionSheet.tag;
    if (buttonIndex == 0)
    {
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if(authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted ) {
            UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:@"请前往设置打开相机权限" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [controller dismissViewControllerAnimated:YES completion:nil];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [controller dismissViewControllerAnimated:YES completion:nil];
            }];
            [controller addAction:confirmAction];
            [controller addAction:cancelAction];
            [self presentViewController:controller animated:YES completion:nil];
            return;
        }
        SCNavigationController *nav = [[SCNavigationController alloc] init];
        nav.scNaigationDelegate = self;
        [nav showCameraWithParentController:self];
    }
    else if (buttonIndex == 1)
    {
        if (self.selectIndex >= [self.imageArray_selected count])
        {
            self.picker = [[ZYQAssetPickerController alloc]init];
            
            self.picker.maximumNumberOfSelection = MAXIMAGENUM - self.imageArray_selected.count;
            self.picker.assetsFilter = [ALAssetsFilter allPhotos];
            self.picker.showEmptyGroups = NO;
            self.picker.delegate = self;
            self.picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings){
                if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypeVideo]) {
                    NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
                    return duration >= 5;
                }else{
                    return  YES;
                }
            }];
            [self presentViewController:self.picker animated:YES completion:^{
                
            }];
        }
        else
        {
            self.picker = [[ZYQAssetPickerController alloc]init];
            
            self.picker.maximumNumberOfSelection = 1;
            self.picker.assetsFilter = [ALAssetsFilter allPhotos];
            self.picker.showEmptyGroups = NO;
            self.picker.delegate = self;
            self.picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings){
                if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypeVideo]) {
                    NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
                    return duration >= 5;
                }else{
                    return  YES;
                }
            }];
            [self presentViewController:self.picker animated:YES completion:^{
                
            }];

        }
    }
    else if(buttonIndex == 2)
    {
        if(actionSheet.cancelButtonIndex != buttonIndex)
        {
            [self.imageArray_selected removeObjectAtIndex:self.selectIndex];
            [self reloadImageData];
        }
    }
}

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
//    [self.scrollview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
//    NSLog(@"self.itemArray is %d",self.photoMenuItems.count);
    [self.picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    for(int i=0; i < assets.count;i++)
    {
        ALAsset *asset=assets[i];
        UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [imageArray addObject:tempImg];
    }
    if ([self.imageArray_selected count] > self.selectIndex && [assets count] == 1)
    {
        [self.imageArray_selected replaceObjectAtIndex:self.selectIndex withObject:[imageArray firstObject]];
    }
    else
    {
        [self.imageArray_selected addObjectsFromArray:imageArray];
    }
    NSLog(@"assets is %zi",assets.count);
    [self reloadImageData];
    
}

- (void)reloadImageData
{
    switch (self.imageArray_selected.count) {
        case 0:
            _selectbtn2.hidden = YES;
            _selectbtn3.hidden = YES;
            _selectbtn4.hidden = YES;
            _selectbtn5.hidden = YES;
            _selectbtn6.hidden = YES;
            [btnSelectImage setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
            break;
        case 1:
            _selectbtn2.hidden = NO;
            _selectbtn3.hidden = YES;
            _selectbtn4.hidden = YES;
            _selectbtn5.hidden = YES;
            _selectbtn6.hidden = YES;
            [_selectbtn2 setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
            
            break;
        case 2:
            _selectbtn2.hidden = NO;
            _selectbtn3.hidden = NO;
            _selectbtn4.hidden = YES;
            _selectbtn5.hidden = YES;
            _selectbtn6.hidden = YES;
            [_selectbtn3 setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
            
            break;
        case 3:
            _selectbtn2.hidden = NO;
            _selectbtn3.hidden = NO;
            _selectbtn4.hidden = NO;
            _selectbtn5.hidden = YES;
            _selectbtn6.hidden = YES;
            [_selectbtn4 setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
            
            break;
        case 4:
            _selectbtn2.hidden = NO;
            _selectbtn3.hidden = NO;
            _selectbtn4.hidden = NO;
            _selectbtn5.hidden = NO;
            _selectbtn6.hidden = YES;
            [_selectbtn5 setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
            
            break;
        case 5:
            _selectbtn2.hidden = NO;
            _selectbtn3.hidden = NO;
            _selectbtn4.hidden = NO;
            _selectbtn5.hidden = NO;
            _selectbtn6.hidden = NO;
            [_selectbtn6 setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
            break;
        case 6:
            _selectbtn2.hidden = NO;
            _selectbtn3.hidden = NO;
            _selectbtn4.hidden = NO;
            _selectbtn5.hidden = NO;
            _selectbtn6.hidden = NO;
        default:
            break;
    }

    for(int i=0;i<self.imageArray_selected.count;i++)
    {
        UIImage *tempImg = self.imageArray_selected[i];
        switch (i) {
            case 0:
                [btnSelectImage setBackgroundImage:tempImg forState:UIControlStateNormal];
                break;
            case 1:
                [_selectbtn2 setBackgroundImage:tempImg forState:UIControlStateNormal];
                break;
            case 2:
                [_selectbtn3 setBackgroundImage:tempImg forState:UIControlStateNormal];
                break;
            case 3:
                [_selectbtn4 setBackgroundImage:tempImg forState:UIControlStateNormal];
                break;
            case 4:
                [_selectbtn5 setBackgroundImage:tempImg forState:UIControlStateNormal];      
                break;
            case 5:
                [_selectbtn6 setBackgroundImage:tempImg forState:UIControlStateNormal];
                break;
                
            default:
                break;
        }
    }
    if ([self.imageArray_selected count] == 0 && _selectIndex == 0)
    {
        _selectbtn2.hidden = YES;
        _selectbtn3.hidden = YES;
        _selectbtn4.hidden = YES;
        _selectbtn5.hidden = YES;
        _selectbtn6.hidden = YES;
        [btnSelectImage setBackgroundImage:[UIImage imageNamed:@"image_plus.png"] forState:UIControlStateNormal];
    }
}


- (void)imageSelected:(UIImage*)img {
    if ([self.imageArray_selected count] > self.selectIndex)
    {
        [self.imageArray_selected replaceObjectAtIndex:self.selectIndex withObject:img];
    }
    else
    {
        [self.imageArray_selected addObject:img];
    }
    [self reloadImageData];
}

- (void)imageSelectionCancelled {
    //[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveAction:(id)sender {
    [self uploadFound];
}

- (void)configureNotification:(BOOL)toAdd {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationTakePicture object:nil];
    if (toAdd) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callbackNotificationForFilter:) name:kNotificationTakePicture object:nil];
    }
}

- (void)callbackNotificationForFilter:(NSNotification*)noti {
    UIViewController *cameraCon = noti.object;
    if (!cameraCon) {
        return;
    }
    UIImage *finalImage = [noti.userInfo objectForKey:kImage];
    if (!finalImage) {
        return;
    }
    PostViewController *con = [[PostViewController alloc] init];
    con.postImage = finalImage;
    
    if (cameraCon.navigationController) {
        [cameraCon.navigationController pushViewController:con animated:YES];
    } else {
        [cameraCon presentViewController:con animated:YES completion:^{
            ;
        }];
    }
}

#pragma mark - SCNavigationController delegate
- (void)didTakePicture:(SCNavigationController *)navigationController image:(UIImage *)image {
    PostViewController *con = [[PostViewController alloc] init];
    con.postImage = image;
    con.recVC = self;
    con.scNC = navigationController;
    [navigationController pushViewController:con animated:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
//    if (textField == self.textFieldSite) {
//        NSString *site = [LocationManagement sharedInstance].address;
//        self.textFieldSite.text = site;
//        return NO;
//    }
    return YES;
}

- (IBAction)setLocationInfo:(id)sender {
    NSString *site = [LocationManagement sharedInstance].address;
    self.textFieldSite.text = site;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    return YES;
}

- (void)uploadFound {
    
    /*
     userid：用户id 必填
     content：内容
     parkid：公园id
     longitude: 经度
     latitude：纬度
     roadname: 路名称
     Filedata：游记图片 必填
     */
    [self.view endEditing:YES];
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO)
    {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    if ([textViewTitle.text isEqualToString:@""])
    {
        ALERT_ERR_MSG(@"游记文字不能为空");
        return;
    }if ([self.imageArray_selected count] == 0)
    {
        ALERT_ERR_MSG(@"请选择图片");
        return;
    }
    
    [self showLoadingView:YES];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UserEntity *userEntity = [UserEntity sharedInstance];
            NSString *longitude = [NSString stringWithFormat:@"%f", [LocationManagement sharedInstance].location.coordinate.longitude];
            NSString *latitude = [NSString stringWithFormat:@"%f", [LocationManagement sharedInstance].location.coordinate.latitude];
            if (self.parkEntity == nil)
            {
                self.parkEntity = [[ParkEntity alloc]init];
                self.parkEntity.ID = @"";
            }
            if (self.ID.length <= 0)
            {
                self.ID = @"";
            }
            if (longitude.length <= 0)
            {
                longitude = @"";
            }
            if (latitude.length <= 0)
            {
                latitude = @"";
            }
            NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                   textViewTitle.text, @"content",
                                   self.parkEntity.ID, @"parkid",
                                   longitude, @"longitude",
                                   latitude, @"latitude",
                                   textFieldSite.text, @"roadname",
                                   userEntity.userId, @"userid",
                                   self.ID,@"activity_id",
                                   [NSString stringWithFormat:@"%zi",[self.imageArray_selected count]],@"file_count",
                                   nil];
            NSMutableArray *filenameArray = [[NSMutableArray alloc]init];
            NSMutableArray *imageDataArray = [[NSMutableArray alloc]init];
            for (int i = 0 ; i < [self.imageArray_selected count]; i++)
            {
                UIImage *tempImg = self.imageArray_selected[i];
                [filenameArray addObject:[NSString stringWithFormat:@"img_%d%@",i,[LPUtils NSDateToNSString:[NSDate date]]]];
                [imageDataArray addObject:UIImageJPEGRepresentation(tempImg, 0.5)];
            }
            
//            NSString *fileName = [NSString stringWithFormat:@"img_%@",[LPUtils NSDateToNSString:[NSDate date]]];
            
            NSDictionary *dicRes = [CommonService uploadUserYJ:param FileName:filenameArray
                                                         Image:imageDataArray];

            [self performSelectorOnMainThread:@selector(showLoadingView:) withObject:NO waitUntilDone:YES];
            
            if (dicRes != nil)
            {
                NSNumber *code = [dicRes objectForKey:@"code"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //
                    if ([code intValue] == 0 && dicRes != nil) {
                        //[self saveUserInfo];
                        [[NSNotificationCenter defaultCenter]postNotificationName:Activity_refresh object:nil];
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"游记上传成功" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
                        [alertView show];
                        alertView.delegate = self;
                        alertView.tag = 1001;
                        [filenameArray removeAllObjects];
                        [imageDataArray removeAllObjects];
                    } else {
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"游记上传失败" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
                        [alertView show];
                    }
                });

            } else
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"游记上传失败" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
                [alertView show];
            }
        });

}

- (IBAction)choosePark:(id)sender {
    [self.view endEditing:YES];
    SelectParkViewController *vc = [[SelectParkViewController alloc] init];
    vc.rfVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RecFoundViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"RecFoundViewController"];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
@end
